package com.eryos.android.cigarettecounter;

/**
 * Project :  CigaretteCounter
 * Author :   Olivier Combe 
 * URL :      http://eryos.fr/CigaretteCounter/
 *
 * Copyright (C) 2011 - Olivier Combe 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

//import android.os.Bundle;
//import android.view.View;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.eryos.android.cigarettecounter.beans.SmokeTime;
import com.eryos.android.cigarettecounter.io.Preferences;

public class CigaretteCounter extends RootActivity {

	/** *************** Static Variables *************** **/	
	private final static String NA_LABEL 	= "NA";
	private final static String LOG_TAG 	= "CigaretteCounter";
	
    /** *************** Instance Variables *************** **/	
    private float cigarettePrice = 0;
    private int dailyCount = 0;
    private double weekAvg = 0;
    private double monthAvg = 0;
    private SmokeTime last = new SmokeTime();
    private SmokeTime delay = new SmokeTime();
    private String cigarette 	= "";
    private String day = "";
    private String hour = "";
    private String minute = "";
    private String minutes = "";
    
    /** *************** UI Elements *************** **/
    private TextView dailyCountValue;
    private TextView delayValue;
    private TextView lastCigValue;
    private TextView avgWeekValue;
    private TextView avgMonthValue;
	
    private Button addCigaretteButton; 
    private Button showWeeklyStatButton; 
    private Button showMonthlyStatButton; 
    
    /** *************** *********** *************** **/
    
    /**
     * init Values ( not UI ) for this activiry from DB / Network / etc.
     */
    public void initValues(){
    	/* Retrieve the Cigarette price */
    	Preferences pref = new Preferences(getSharedPreferences(PREFS_NAME, 0));
    	pref.readParamFromFile();
    	cigarettePrice = pref.getCigarettePrice();
    	
    	/* Refresh the UI with DB values */
    	retieveDataFromDB();
    }
    
    /**
     * Method used to refresh the Daily Counter  
     */
    public void showDailyCount(){    	
    	String currentValue = dailyCount+" "+cigarette;
    	dailyCountValue.setText(currentValue);

    }
    
    /**
     * Method used to refresh the Weekly Average  
     */
    public void showWeeklyAverage(){
    	String weekValueLabel = weekAvg+" "+cigarette+" / "+day;
    	if ( weekAvg <= 0 )
    		avgWeekValue.setText(NA_LABEL);
    	else
    		avgWeekValue.setText(weekValueLabel);
    }
    
    /**
     * Method used to refresh the Monthly Average  
     */
    public void showMonthlyAverage(){
    	String monthValueLabel = monthAvg+" "+cigarette+" / "+day;
    	if ( monthAvg <= 0 )
    		avgMonthValue.setText(NA_LABEL);
    	else
    		avgMonthValue.setText(monthValueLabel);
    }
    
    /**
     * Method used to refresh the Delay since Last Cigarette  
     */
    public void showDelaySinceLast(){
    	String lastLabel = "" ;
    	if ( last.getHour() == 0 )
    		lastLabel = last.getMinute()+" "+minute+" ("+last.getTotalMinutes()+" "+minutes+")";//getResources().getString(R.string.home_delay_last_value_short);
    	else
    		lastLabel = last.getHour()+" "+hour+" "+last.getMinute()+" "+minute+" ("+last.getTotalMinutes()+" "+minutes+")";//getResources().getString(R.string.home_delay_last_value);

    	//lastLabel = lastLabel.replaceAll("#1", last.getHour()+"").replaceAll("#2", last.getMinute()+"").replaceAll("#3", last.getTotalMinutes()+"");
    	
    	if ( last != null && last.getTotalMinutes() < 0 )
    		lastCigValue.setText(NA_LABEL);
    	else
    		lastCigValue.setText(lastLabel);
    }
    
    /**
     * Method used to refresh the Average delay between 2 cigarettes  
     */
    public void showAverageDelay(){
    	String delayLabel = "";
    	if ( delay.getHour() == 0 )
    		delayLabel = delay.getMinute()+" "+minute+" ("+delay.getTotalMinutes()+" "+minutes+")";//getResources().getString(R.string.home_delay_last_value_short);
    	else
    		delayLabel = delay.getHour()+" "+hour+" "+delay.getMinute()+" "+minute+" ("+delay.getTotalMinutes()+" "+minutes+")";//getResources().getString(R.string.home_delay_last_value);

//    	if ( delay.getHour() == 0 )
//    		delayLabel = getResources().getString(R.string.home_average_delay_value_short);
//    	else
//    		delayLabel = getResources().getString(R.string.home_average_delay_value);
//
//    	delayLabel = delayLabel.replaceAll("#1", delay.getHour()+"").replaceAll("#2", delay.getMinute()+"").replaceAll("#3", delay.getTotalMinutes()+"");

    	if ( delay != null && delay.getTotalMinutes() <= 0 )
    		delayValue.setText(NA_LABEL);
    	else
    		delayValue.setText(delayLabel);
    } 
    

    
    /**
     * Init all UI elements
     */
    public void initUI(){
        setContentView(R.layout.main);

        addCigaretteButton 		= (Button) findViewById(R.id.home_add_cigarette_button);
        showWeeklyStatButton 	= (Button) findViewById(R.id.home_button_history_week); 
        showMonthlyStatButton 	= (Button) findViewById(R.id.home_button_history_month);
        
        dailyCountValue = (TextView) findViewById(R.id.home_daily_count_value_field);
        delayValue 		= (TextView) findViewById(R.id.home_average_delay_value_field);
        lastCigValue 	= (TextView) findViewById(R.id.home_delay_last_value_field);
        avgWeekValue	= (TextView) findViewById(R.id.home_week_average_value_field);
        avgMonthValue	= (TextView) findViewById(R.id.home_month_average_value_field);
        
        cigarette 	= getResources().getString(R.string.cigarette);
        day 	  	= getResources().getString(R.string.day);
        hour 		= getResources().getString(R.string.hour);
        minute 	  	= getResources().getString(R.string.minute);
        minutes	  	= getResources().getString(R.string.minutes);
    }    
    
    /**
     * Method used to update the UI after called to initValues()
     */
    public void updateUI(){
    	
    	showDailyCount();
    	
    	showDelaySinceLast();
    	
    	showAverageDelay();
    	
    	showWeeklyAverage();
    	
    	showMonthlyAverage();

    
    }
    
    /**
     * Method used to show/refresh all values on Main View
     */
    public void retieveDataFromDB(){
    	
    	dailyCount = db.getDailyCount();
    	
    	weekAvg = db.getWeeklyAverage();
    	
    	monthAvg = db.getMonthlyAverage();
    	
    	last = db.getDelaySinceLast();
    	
    	delay = db.getAverageDelay();
    }
        
    /**
     * Method called when a click is made on the "+1 button"
     */
    public void clickAddButton(){
    	Log.d(LOG_TAG, "Click on Add Button");
    	
    	/* Insert current TimeStamp */
    	db.insertCurrentTimestamp("", cigarettePrice);

    	/* Retrieve data from DB */
    	retieveDataFromDB();
    	
    	/* Update UI values */
    	updateUI();
    	
    	/* Update Widgets (if some exists ) */
    	CigaretteWidget.updateWidgets(this);
    	
    	/* Display a quick message */
    	Toast.makeText(this, R.string.home_insert_OK, Toast.LENGTH_SHORT).show();
    }

	/**
	 * Method used to defined all UI handlers
	 */
    public void initHandlers(){
        // Listeners & Handlers 
        addCigaretteButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(LOG_TAG, "Click Add Button");
            	clickAddButton();
            }
        });
        
        showWeeklyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(LOG_TAG, "Click Weekly Stats Button");
            	showView(VIEW.WEEKLY);
            }
        });
        
        showMonthlyStatButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	Log.d(LOG_TAG, "Click Monthly Stats Button");
            	showView(VIEW.MONTHLY);
            }
        });
    }

}
